package com.javafactroy.kunlong.bip.icp.context.connpool.testframe;

import com.javafactroy.kunlong.bip.icp.common.config.BipPoolConfig;
import com.javafactroy.kunlong.bip.icp.message.test.base.TMsg;
import com.javafactroy.kunlong.bip.icp.message.test.netty.NettyClientTMsg;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Data
@Slf4j
public class NettyClientTMsgPool {

    @Autowired
    NettyClientTMsgPoolFactory factory;
    @Autowired
    BipPoolConfig poolConfig;

    static volatile GenericObjectPool<NettyClientTMsg> objectPool;

    public NettyClientTMsgPool() {

    }

    public void setIpPort(String ip, int port) {
        getFactory().getBipConfig().setIpPort(ip, port);

    }

    GenericObjectPool<NettyClientTMsg> getPool() {
        if (objectPool == null) {
            synchronized (NettyClientTMsgPool.class) {
                if (objectPool == null) {
                    objectPool = new GenericObjectPool<NettyClientTMsg>(factory, poolConfig);
                }
            }
        }
        return objectPool;
    }

    public NettyClientTMsg borrowObject() throws Exception {

        return getPool().borrowObject();
    }

    public void returnObject(NettyClientTMsg client) {

        getPool().returnObject(client);

    }

    public TMsg sendTMsg(TMsg req) throws Exception {
        NettyClientTMsg nettyClient = borrowObject();
        try {
            return nettyClient.sendTMsg(req);
        } finally {
            returnObject(nettyClient);
        }
    }

}










